

#include "spear.h"
#include "bullet.h"
#include "army.h"
#include "gamemanager.h"
#include "CCSkeletalSprite.h"
#include "gamescene.h"

#define __super         Unit

Spear::Spear() {

}

Spear::~Spear() {

}

void Spear::init(UnitInfo const &info, float unitScale) {
	__super::init(info, unitScale);
}

void Spear::update(float ticks) {
	__super::update(ticks);
}

void Spear::handleStateBirth(float ticks) {
	transformState(UnitState::idle);
}

void Spear::handleStateAim(float ticks) {

}

void Spear::handleStateAttack(float ticks) {
	if (sprite->animationIsDone()) {
		transformState(UnitState::idle);
	}
}

void Spear::handleStateDying(float ticks) {
	if (sprite->animationIsDone()) {
		transformState(UnitState::died);
	}
}

void Spear::handleStateIdle(float ticks) {
	if (gameScene->battleState == BattleState::standby) {
		return;
	}

	if (gridInfo.globalLineIndex == ourArmy->frontLine && target) {
		transformState(UnitState::attack);
	} else {
		if (findDistantOpponent()) {
			transformState(UnitState::attack);
		}
	}
}

void Spear::handleStateAssign(float ticks) {
	move(ticks);

	if (arrivedTargetPosition) {
		transformState(UnitState::idle);
	}
}

void Spear::handleStateWalk(float ticks) {
	if(gameScene->battleState == BattleState::standby) {
		transformState(UnitState::idle);
	} else {
		move(ticks);

		if (arrivedTargetPosition) {
			transformState(UnitState::idle);
		} else {
			if (gridInfo.globalLineIndex == ourArmy->frontLine && target) {
				transformState(UnitState::attack);
			} else {
				if (findDistantOpponent()) {
					transformState(UnitState::attack);
				}
			}
		}
	}
}

void Spear::handleStateWalkAim(float ticks) {

}

void Spear::handleStateWalkAttack(float ticks) {
	move(ticks);

	if (sprite->animationIsDone()) {
		if (arrivedTargetPosition) {
			transformState(UnitState::idle);
		} else {
			transformState(UnitState::walk);
		}
	}
}

void Spear::onEnterState(UnitState theState) {
	__super::onEnterState(theState);

	if (theState == UnitState::walk_reload) {
		sprite->playAnimation("walk");
		sprite->setLoopCount(-1);
	} else if (theState == UnitState::reload) {
		sprite->playAnimation("idle");
		sprite->setLoopCount(-1);
	}
}

void Spear::startAttack() {
	Unit::startAttack();
}
